<?php
header('Content-type: text/html;charset=utf-8');

// 发送模板短信
function _sendsmscode($phone, $tpl_id, $params){
    define('BASE_MOCLOUD_USER', ''); //前往魔云开放平台注册账号
    define('BASE_MOCLOUD_PASS', ''); //前往魔云开放平台注册账号

    $data = httpRequest('post', 'http://ocr.xinby.cn/api.php', array(
        'user' => BASE_MOCLOUD_USER,
        'pass' => BASE_MOCLOUD_PASS,
        'act' => 'sms',
        'type' => 'send',
        'phone' => $phone,
        'tpl_id' => $tpl_id,
        'tpl_params' => json_encode($params),
    ));
    if ($data['http_code'] !== 200){
        return '发送失败';
    }
    $data = json_decode($data['response']);
    if ($data->code === 1){
        return '发送成功';
    }
    return '失败, 原因:'.$data->errmsg;
}

// HTTP 请求
function httpRequest($method, $url, $post_data = '')
{
    $method = strtolower($method);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, '0');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, '0');
    if ($method === 'get') {
        // get method
    } else if ($method === 'post') {
        // post method
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
    } else {
        return false;
    }
    $output = curl_exec($ch);
    if ($output === false) {
        return false;
    }
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    $header = substr($output, 0, $header_size);
    $response = substr($output, $header_size);
    curl_close($ch);
    return array(
        'http_code' => $http_code,
        'header' => $header,
        'response' => $response,
    );
}

// 调用函数
_sendsmscode('13185808318', '1', array(
    'code' => rand(100000, 999999),
    'type' => '身份验证',
));

// 【凌空网络】验证码：989611，您正在进行身份验证，15分钟内有效。